#!/bin/bash
set -x -e
KERNELVERSION=6.1
KERNEL=linux-source-$KERNELVERSION
CONFIG=config-$(uname -m)
AUFS=aufs5-standalone
CHECKOUT=origin/aufs6.1

CWD=$(pwd)

# add unstable debian repo
#if [ "$(cat /etc/apt/sources.list | grep unstable)" = "" ]; then
#   echo "deb http://deb.debian.org/debian unstable main contrib non-free " | tee -a /etc/apt/sources.list
#   echo "deb-src http://deb.debian.org/debian unstable main contrib non-free" | tee -a /etc/apt/sources.list
#fi

apt update

apt install build-essential $KERNEL bc kmod cpio flex libncurses5-dev libelf-dev libssl-dev dwarves bison git rsync python3 openssl

cd /usr/src
tar -xf $KERNEL.tar.xz

cd $KERNEL
cat $CWD/$CONFIG > .config

rm -Rf $AUFS
git -c http.sslVerify=false clone https://github.com/sfjro/$AUFS
cd $AUFS
git checkout $CHECKOUT
cd ..

cp -aR $AUFS/fs .
cp -a $AUFS/include/uapi/linux/aufs_type.h include/uapi/linux

patch -p1 < $AUFS/aufs6-kbuild.patch
patch -p1 < $AUFS/aufs6-base.patch
patch -p1 < $AUFS/aufs6-mmap.patch
patch -p1 < $AUFS/aufs6-standalone.patch
patch -p1 < $AUFS/aufs6-loopback.patch
patch -p1 < $AUFS/vfs-ino.patch
patch -p1 < $AUFS/tmpfs-idr.patch

echo "CONFIG_AUFS_FS=m
# CONFIG_AUFS_BRANCH_MAX_127 is not set
# CONFIG_AUFS_BRANCH_MAX_511 is not set
# CONFIG_AUFS_BRANCH_MAX_1023 is not set
CONFIG_AUFS_BRANCH_MAX_32767=y
CONFIG_AUFS_SBILIST=y
# CONFIG_AUFS_HNOTIFY is not set
CONFIG_AUFS_EXPORT=y
CONFIG_AUFS_INO_T_64=y
CONFIG_AUFS_XATTR=y
# CONFIG_AUFS_FHSM is not set
# CONFIG_AUFS_RDU is not set
CONFIG_AUFS_DIRREN=y
CONFIG_AUFS_SHWH=y
CONFIG_AUFS_BR_RAMFS=y
CONFIG_AUFS_BR_FUSE=y
CONFIG_AUFS_POLL=y
CONFIG_AUFS_BR_HFSPLUS=y
CONFIG_AUFS_BDEV_LOOP=y
# CONFIG_AUFS_DEBUG is not set
CONFIG_NTFS3_FS=m
CONFIG_NTFS3_LZX_XPRESS=y
# CONFIG_NTFS3_FS_POSIX_ACL is not set
" >>.config

make menuconfig
make -j4 bindeb-pkg

cd ..

echo "You can find debian package in /usr/src"
